import api from '@/api'
import { deepCopy, setPage } from '@/utils/util'

const initPage = {
    size: 10,
    number: 0,
    total: 0,
    pages: 0,
    filter: {
        enabled: null,
        classIds: null,
        name: null
    }
}

const state = {
    data: {
        transClasses: [],
        transactions: [],
        transactionItems: []
    },
    ui: {
        page: deepCopy(initPage)
    }
}

// getters
const getters = {
    // Data
    transClasses: state => state.data.transClasses,
    transactions: state => state.data.transactions,
    // UI
    transTotal: state => state.ui.page.total
}

// actions
const actions = {
    getTransClasses({ commit }) {
        api.getClassifications('key_class_transaction', {
            loading: true,
            success: transClasses => {
                commit('setTransClasses', {
                    transClasses
                })
            }
        })
    },
    saveTransClass({ dispatch }, data) {
        api.saveClassification(
            {
                ...data,
                classType: 'key_class_transaction'
            },
            {
                success: () => {
                    dispatch('getTransClasses')
                }
            }
        )
    },
    removeTransClass({ dispatch }, id) {
        api.removeClassification(id, {
            success: () => {
                dispatch('getTransClasses')
            }
        })
    },
    getTransactions({ commit, state }, page) {
        api.getTransactions(page ? page : state.ui.page, {
            loading: true,
            success: res => {
                const { pages, total } = res
                commit('setTransPage', {
                    pages,
                    total
                })
                commit('setTransactions', res)
            }
        })
    },
    saveTransaction({ dispatch }, data) {
        api.saveTransaction(data, {
            success: () => {
                dispatch('getTransactions')
            }
        })
    },
    removeTransactions({ dispatch }, ids) {
        api.removeTransactions(ids, {
            success: () => {
                dispatch('getTransactions')
            }
        })
    }
}

// mutations
const mutations = {
    setTransClasses: (state, payload) => {
        console.log(payload)
        state.data.transClasses = payload.transClasses
    },
    setTransactions: (state, payload) => {
        state.data.transactions = payload.content
    },
    setTransPage: (state, page) => {
        console.log(page)
        page && setPage(state.ui.page, page)
    },
    resetTransPage: state => {
        state.ui.page = deepCopy(initPage)
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}
